//
//  CZEmoticonView.swift
//  git
//
//  Created by 徐 鹏超 on 16/4/16.
//  Copyright © 2016年 徐 鹏飞. All rights reserved.
//

import UIKit
let CZEmoticonViewReuseIdentifier = "CZEmoticonViewReuseIdentifier"

class CZEmoticonView: UIView ,UICollectionViewDataSource,CZEmoticonFooterViewDelegate{

    override init(frame: CGRect) {
        super.init(frame:frame)
        
        setupUI()
        setupCollectionView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        addSubview(footerView)
        addSubview(collectionView)
        
        
        
        
        // 设置约束
        footerView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(self.snp_bottom)
            
            make.height.equalTo(44)
        }
        collectionView.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(self.snp_left)
            make.top.equalTo(self.snp_top)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(footerView.snp_top)
        }
    }
    
    private func setupCollectionView(){
        collectionView.registerClass(CZEmoticonViewCollectionCell.self, forCellWithReuseIdentifier: CZEmoticonViewReuseIdentifier)
        
        collectionView.dataSource = self
        collectionView.pagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        // 设置流水布局的大小
        // cell整个填充 collectionView
        //做为一个小白,可以写几行代码就运行看一下效果,如果效果错误,就解决那几行代码
        //        print(collectionView.frame.size)
        
        //        flowLayout.itemSize = collectionView.frame.size
        
        // 设置滚动方法 需要设置flowLayout
        flowLayout.scrollDirection = .Horizontal
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        flowLayout.itemSize = collectionView.frame.size
    }
    
    //MARK:--懒加载
    // 底部切换视图
    private lazy var footerView: CZEmoticonFooterView = {
        
        let footerView = CZEmoticonFooterView()
        
        footerView.delegate = self
        
        return footerView
    }()
    
    // 定义一个流水布局
    private lazy var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    // 由于 flowlayout是一个懒加载,所以需要在调用的时候用一下 self
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowLayout)
}

extension CZEmoticonView{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return CZEmoticonManager.getAllEmoticon()[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CZEmoticonViewReuseIdentifier, forIndexPath: indexPath)as! CZEmoticonViewCollectionCell
        
        cell.label.text = "第\(indexPath.section)部分 第\(indexPath.item)个cell"
        
        let emoticons = CZEmoticonManager.getAllEmoticon()[indexPath.section][indexPath.item]
        
        cell.emoticons = emoticons
        
        return cell
        
    }
    
    
     func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{
        return CZEmoticonManager.getAllEmoticon().count
    }
    
    
    
}

class CZEmoticonViewCollectionCell:UICollectionViewCell {
    // 定义一个盛放按钮的数组,用户给按钮赋值使用
    private lazy var emoticonButtons: [CZEmoticonButton] = [CZEmoticonButton]()
    
    var emoticons:[CZEmoticon]?{
        didSet{
            for button in emoticonButtons{
                button.hidden = true
            }
            for (index,emoticon) in emoticons!.enumerate(){
                let button = emoticonButtons[index]
                
                button.emoticon = emoticon
                
                button.hidden = false
                
                if let emoji = emoticon.emoji{
                    button.setTitle(emoji, forState: UIControlState.Normal)
                    
                    button.titleLabel?.font = UIFont.systemFontOfSize(38)
                }else{
                    button.setTitle(nil, forState: UIControlState.Normal)
                }
                if let png = emoticon.png {
                    
                    // 有图片的名字
                    // 需要拼接它的路径
                    let imagePath = "\(emoticon.path!)/\(png)"
                    // 一定要注意图片的路径中不要有可选项
                    print(imagePath)
                    button.setImage(UIImage(named: imagePath), forState: UIControlState.Normal)
                    
                } else {
                    button.setImage(nil, forState: UIControlState.Normal)
                }

            }
            
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
//        addSubview(label)
        
        backgroundColor = UIColor.grayColor()
        
//        label.frame = bounds
        
        addEmoticon()
    }
    
    
    //添加表情按钮
    private func addEmoticon(){
        // 添加20个按钮, 另外一个删除按钮,我们单独添加
        
        let buttonWidth = bounds.width / 7
        let buttonHeigh = bounds.height / 3
        
        
        for i in 0..<20{
            
            let button = CZEmoticonButton(type: UIButtonType.Custom)
            
            //            button.setTitle("\(i)", forState: UIControlState.Normal)
            // 按钮的默认颜色是白色
            button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
            
//            button.setBackgroundImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            
            button.addTarget(self, action: "clickButton:", forControlEvents: UIControlEvents.TouchUpInside)
            // 修改按钮的位置
            //  5
            let x = CGFloat(i%7) * buttonWidth
            let y = CGFloat(i/7) * buttonHeigh
            
            button.frame = CGRectMake(x,y,buttonWidth,buttonHeigh)
            
            contentView.addSubview(button)
            
            emoticonButtons.append(button)
            
            
        }
        
        // 添加删除按钮
        contentView.addSubview(deleteButton)
        
        deleteButton.frame = CGRectMake(bounds.size.width - buttonWidth,bounds.size.height - buttonHeigh,buttonWidth,buttonHeigh)
        
        
        
    }
    
    //MARK:--按钮的点击方法
    @objc private func clickButton(button: CZEmoticonButton){
        
        
        print(button)
        // 如果想扩展系统的属性的话,继承自这个类,然后可以添加属性
        //        button.emoticon
        if let emoticon = button.emoticon {
            
            // 最近表情的添加
            //            CZEmoticonManager.recentEmoticon.append(emoticon)
            CZEmoticonManager.addRecentEmoticon(emoticon)
            
            NSNotificationCenter.defaultCenter().postNotificationName(kNotificationEmoticon, object: nil, userInfo: ["emoticon": emoticon])
        }
    }
    
    
    //MARK:--懒加载
    // 添加一个测试的Label
    private lazy var label = UILabel()
    //删除按钮
    private lazy var deleteButton: UIButton = {
        
        let button = UIButton(type: UIButtonType.Custom)
        
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        
        
        return button
    }()

}

extension CZEmoticonView{
    
    func emoticonToolBarButtonDidSelected(type: EmoticonType){
        
        switch type{
        case .Recent :let index = NSIndexPath(forItem: 0, inSection: 0)
            collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        case .Default:
            let index = NSIndexPath(forItem: 0, inSection: 1)
            collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        case .Emoji:
            let index = NSIndexPath(forItem: 0, inSection: 2)
            collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        case .Lxh:
            let index = NSIndexPath(forItem: 0, inSection: 3)
            collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        default: break
  
            
            
        }
        
        
    }
    
    
    
    
}







